import { ref, computed, resolveComponent } from 'vue'
import { defineStore } from 'pinia'
import { generateProjectDescription, generateWorkflow, generateCode, generateDeployGuide, donwloadProject, postWorkflow } from '@/api/llm'
import { v4 as uuidv4 } from 'uuid'
import { removeHistoryItem } from '@/api/llm'
import { postProjectDescription } from '@/api/llm'

export const useHistoryStore = defineStore('history', () => {
  // 历史记录列表
  const historyList = ref([]);

  // 当前活跃的历史记录ID
  const activeHistoryId = ref('');

  // 当前的响应内容
  const currentResponse = ref('');

  // 工作流结构
  const currentWorkflow = ref(null);

  // 生成的代码
  const currentCode = ref('');
  const currentFileTree = computed(() => {
    const tree = buildFileTree(currentCode.value.pathList);
    currentShowCode.value = ''
    return tree
  })
  const currentShowCode = ref('')

  // 部署指南
  const currentDeployGuide = ref('');

  // 当前处于哪个步骤（初始需求、扩展需求、工作流、代码、部署说明）
  const currentStep = ref('initial'); // 'initial', 'requirement', 'workflow', 'code', 'deploy'

  // 根据ID获取历史记录
  const getHistoryById = (id) => {
    return historyList.value.find(item => item.id === id);
  };


  // 获取当前活跃的历史记录
  const activeHistory = computed(() => {
    if (!activeHistoryId.value) return null;
    return getHistoryById(activeHistoryId.value);
  });

  // 设置活跃的历史记录
  const setActiveHistory = (id) => {
    activeHistoryId.value = id;
    const history = getHistoryById(id);
    if (history) {
      currentResponse.value = history.response || '';
      currentWorkflow.value = history.workflow || null;
      currentCode.value = history.code || '';
      currentDeployGuide.value = history.deployGuide || '';
      currentStep.value = history.step || 'initial';
    }
  };

  // 添加新的历史记录
  const addHistory = (prompt, response, step = 'initial') => {
    const id = uuidv4();
    const timestamp = new Date().toISOString();

    const newHistory = {
      id,
      prompt,
      response,
      timestamp,
      step,
      workflow: null,
      code: '',
      deployGuide: ''
    };

    historyList.value.unshift(newHistory); // 添加到最前面
    return id;
  };

  // 更新历史记录
  const updateHistory = (id, newData) => {
    const index = historyList.value.findIndex(item => item.id === id);
    if (index !== -1) {
      historyList.value[index] = {
        ...historyList.value[index],
        ...newData,
        timestamp: new Date().toISOString() // 更新时间戳
      };
    }
  };

  // 删除历史记录
  const removeHistory = (id) => {
    const index = historyList.value.findIndex(item => item.id === id);
    if (index !== -1) {
      console.log("删除历史记录:", historyList.value[index].response.intentionID)
      removeHistoryItem(historyList.value[index].response.intentionID)
      historyList.value.splice(index, 1);

      // 如果删除的是当前活跃的记录，切换到其他记录
      if (id === activeHistoryId.value) {
        if (historyList.value.length > 0) {
          setActiveHistory(historyList.value[0].id);
        } else {
          activeHistoryId.value = '';
          currentResponse.value = '';
          currentWorkflow.value = null;
          currentCode.value = '';
          currentDeployGuide.value = '';
          currentStep.value = 'initial';
        }
      }
    }
  };

  // 创建新对话
  const createNewChat = () => {
    // 重置当前活跃ID和响应内容
    activeHistoryId.value = '';
    currentResponse.value = '';
    currentWorkflow.value = null;
    currentCode.value = '';
    currentDeployGuide.value = '';
    currentStep.value = 'initial';
    currentShowCode.value = '';

  };

  // 提交初始需求
  const submitPrompt = async (prompt) => {
    try {
      // 调用API获取响应
      const response = await generateProjectDescription(prompt);
      // 更新当前响应
      response.data.intention.intentionID = response.data.intentionID
      currentResponse.value = response.data.intention;

      currentStep.value = 'requirement';

      // 如果已有活跃历史记录，则更新
      if (activeHistoryId.value) {
        updateHistory(activeHistoryId.value, {
          prompt,
          response,
          step: 'requirement',
          workflow: null,
          code: '',
          deployGuide: ''
        });
      } else {
        // 否则创建新的历史记录
        const newId = addHistory(prompt, response, 'requirement');
        activeHistoryId.value = newId;
      }

      return response;
    } catch (error) {
      console.error('提交提示词失败:', error);
      throw error;
    }
  };

  // 提交修改后的需求，生成工作流
  const submitRequirement = async (requirement) => {
    try {
      const successSubmitEdited = await postProjectDescription(requirement)
      if (!successSubmitEdited) {
        console.log("项目需求修改失败")
      }
      // 调用API获取工作流
      const workflow = await generateWorkflow(requirement);
      console.log("workflow:", workflow)
      // 确保workflow是对象格式
      let workflowData = typeof workflow === 'string'
        ? JSON.parse(workflow)
        : workflow;
      workflowData = workflowData.data
      // 更新当前工作流和步骤
      currentWorkflow.value = workflowData;
      currentStep.value = 'workflow';

      // 更新历史记录
      if (activeHistoryId.value) {
        updateHistory(activeHistoryId.value, {
          response: requirement, // 更新为修改后的需求
          workflow: workflowData,
          step: 'workflow'
        });
      }

      return workflowData;
    } catch (error) {
      console.error('生成工作流失败:', error);
      throw error;
    }
  };

  // 根据工作流生成代码
  const submitWorkflow = async () => {
    try {
      if (!currentWorkflow.value) {
        throw new Error('没有工作流数据，无法生成代码');
      }
      const postResult = await postWorkflow(currentWorkflow.value)
      if (postResult) {
        console.log("工作流更新成功")
      } else {
        console.log("工作流更新失败")
      }

      // 调用API获取代码
      let response = await generateCode(currentWorkflow.value);
      const codeStr = response.data
      // 更新当前代码和步骤
      currentCode.value = codeStr;
      currentStep.value = 'code';

      // 更新历史记录
      if (activeHistoryId.value) {
        updateHistory(activeHistoryId.value, {
          code: codeStr,
          step: 'code'
        });
      }

      return codeStr;
    } catch (error) {
      console.error('生成代码失败:', error);
      throw error;
    }
  };

  // 生成部署指南
  const submitCodeForDeployGuide = async () => {
    try {
      if (!currentWorkflow.value || !currentCode.value) {
        throw new Error('没有工作流或代码数据，无法生成部署指南');
      }

      // 调用API获取部署指南
      const deployGuide = await generateDeployGuide(currentCode.value);

      // 更新当前部署指南和步骤
      currentDeployGuide.value = deployGuide;
      currentStep.value = 'deploy';

      // 更新历史记录
      if (activeHistoryId.value) {
        updateHistory(activeHistoryId.value, {
          deployGuide,
          step: 'deploy'
        });
      }

      return deployGuide;
    } catch (error) {
      console.error('生成部署指南失败:', error);
      throw error;
    }
  };
  const getAllFile = async () => {
    try {

      const allFileInfo = await donwloadProject(currentCode.value);
      // console.log("info:", allFileInfo)
      // return allFileInfo;
    } catch (error) {
      console.error('下载所有文件失败:', error);
      throw error;
    }
  }

  // 设置当前活跃的历史记录
  const setCurrentHistory = (record) => {
    if (typeof record === 'string') {
      // 如果传入的是ID
      activeHistoryId.value = record;
      const history = getHistoryById(record);
      if (history) {
        currentResponse.value = history.response || '';

        // 确保workflow是对象
        const workflow = history.workflow;
        currentWorkflow.value = workflow || null;

        // 确保code是字符串
        const code = history.code;
        currentCode.value = typeof code === 'string' ? code : (code ? JSON.stringify(code, null, 2) : '');

        currentDeployGuide.value = history.deployGuide || '';
        currentStep.value = history.step || 'initial';
      }
    } else if (record && record.id) {
      // 如果传入的是记录对象
      setActiveHistory(record.id);
    }
  };

  // 清空所有历史记录
  const clearHistory = () => {
    historyList.value = [];
    activeHistoryId.value = '';
    currentResponse.value = '';
    currentWorkflow.value = null;
    currentCode.value = '';
    currentDeployGuide.value = '';
    currentStep.value = 'initial';
  };

  // isLoading状态
  const isLoading = ref(false);

  return {
    currentShowCode,
    currentFileTree,
    getAllFile,
    historyList,
    activeHistoryId,
    currentResponse,
    currentWorkflow,
    currentCode,
    currentDeployGuide,
    currentStep,
    activeHistory,
    setActiveHistory,
    addHistory,
    updateHistory,
    removeHistory,
    clearHistory,
    createNewChat,
    submitPrompt,
    submitRequirement,
    submitWorkflow,
    submitCodeForDeployGuide,
    isLoading,
    // 添加别名方法以兼容组件调用
    setCurrentHistory,
    deleteHistory: removeHistory
  };
});
function buildFileTree(paths) {
  let nextId = 2; // 从ID=2开始分配（根节点ID=1）

  // 创建根节点
  const root = {
    id: 1,
    name: 'files',
    isFolder: true,
    children: []
  };

  // 用于缓存路径节点
  const nodeMap = new Map();
  nodeMap.set('vite', root);

  // 处理每条路径
  paths.forEach(path => {
    // 统一路径分隔符为斜杠
    const normalizedPath = path.replace(/\\/g, '/');
    const parts = normalizedPath.split('/');
    let currentPath = 'vite';
    let parentNode = root;

    // 逐级处理路径的每个部分
    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      const isLast = i === parts.length - 1;
      currentPath += '/' + part;

      // 如果节点不存在则创建
      if (!nodeMap.has(currentPath)) {
        // 检测文件扩展名来判断是否是文件
        const isFile = isLast && part.includes('.');

        const newNode = {
          id: nextId++,
          name: part,
          isFolder: !isFile,
        };

        // 文件节点添加路径属性
        if (isFile) {
          newNode.path = currentPath.replace(/\//g, '//');
        }

        // 添加到父节点
        if (!parentNode.children) {
          parentNode.children = [];
        }
        parentNode.children.push(newNode);

        // 缓存新节点
        nodeMap.set(currentPath, newNode);
      }

      // 准备处理下一级
      const currentNode = nodeMap.get(currentPath);
      if (currentNode.isFolder) {
        parentNode = currentNode;
      }
    }
  });

  return [root];
}